﻿using System;
using Microsoft.Practices.Unity;
using System.Web.Routing;
using Web7.Core.Security.Users;
using Web7.Domain;

namespace Web7.Core.Security
{
    public class Authorizer : IAuthorizer
    {
        [Dependency]
        public IAuthorizationService AuthorizationService { get; set; }

        [Dependency]
        public IAuthenticationService AuthenticationService { get; set; }

        public bool Authorize(Permission permission)
        {
            return Authorize<Entity>(permission, null, null);
        }

        public bool Authorize(Permission permission, string message)
        {
            return Authorize<Entity>(permission, null, message);
        }

        public bool Authorize<T>(Permission permission, T content, string message)
        {
            if (AuthorizationService.TryCheckAccess<T>(permission, AuthenticationService.GetAuthenticatedUser(), content))
            {
                return true;
            }

            if (AuthenticationService.GetAuthenticatedUser() is UserAnonymous)
            {
                if (message != null)
                {
                    //TODO; Anonymous user do not have permission
                }
                else
                {
                    //TODO;nodify
                }
            }
            else
            {
                if (message != null)
                {
                    //TODO; current user do not have permission
                }
                else
                {
                    //TODO;nodify
                    throw new Exception("无权限访问");
                }
            }

            return false;
        }
    }
}
